package org.jeecg.modules.wmhb.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.wmhb.vo.*;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.modules.wmhb.util.WmhbUtil;

/**
 * @Description: 项目表
 * @Author: jeecg-boot
 * @Date: 2024-09-02
 * @Version: V1.0
 */
@Tag(name = "项目表")
@RestController
@RequestMapping("/wmhb/wmProject")
@Slf4j
public class WmProjectController extends JeecgController<WmProject, IWmProjectService> {
    @Autowired
    private IWmProjectService wmProjectService;
    @Autowired
    ISysBaseAPI sysBaseApi;

    /**
     * 分页列表查询
     *
     * @param wmProject
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "项目表-分页列表查询")
    @Operation(summary = "项目表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmProject>> queryPageList(WmProject wmProject,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        QueryWrapper<WmProject> queryWrapper = QueryGenerator.initQueryWrapper(wmProject, req.getParameterMap());
        Page<WmProject> page = new Page<WmProject>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        IPage<WmProject> pageList = wmProjectService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmProject
     * @return
     */
    @AutoLog(value = "项目表-添加")
    @Operation(summary = "项目表-添加")
    @RequiresPermissions("wmhb:wm_project:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmProject wmProject) {
        if (UserConstant.NOT_UNIQUE.equals(wmProjectService.checkCodeUnique(wmProject))) {
            return Result.error("新增项目失败，项目编码已存在");
        }
        if (UserConstant.NOT_UNIQUE.equals(wmProjectService.checkNameUnique(wmProject))) {
            return Result.error("新增项目失败，项目名称已存在");
        }

        if (StringUtils.isEmpty(wmProject.getCode())) {
            String code = (String) FillRuleUtil.executeRule(FillRuleConstant.PROJECT, null);
            wmProject.setCode(code);
        }

        wmProjectService.save(wmProject);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmProject
     * @return
     */
    @AutoLog(value = "项目表-编辑")
    @Operation(summary = "项目表-编辑")
    @RequiresPermissions("wmhb:wm_project:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmProject wmProject) {
        if (UserConstant.NOT_UNIQUE.equals(wmProjectService.checkCodeUnique(wmProject))) {
            return Result.error("编辑项目" + wmProject.getCode() + "失败，项目编码已存在");
        }
        if (UserConstant.NOT_UNIQUE.equals(wmProjectService.checkNameUnique(wmProject))) {
            return Result.error("编辑项目" + wmProject.getCode() + "失败，项目名称已存在");
        }

        wmProjectService.updateById(wmProject);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目表-通过id删除")
    @Operation(summary = "项目表-通过id删除")
    @RequiresPermissions("wmhb:wm_project:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        if (wmProjectService.checkHasItem(id)) {
            return Result.error("项目下有合同，请先删除合同");
        }
        wmProjectService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目表-批量删除")
    @Operation(summary = "项目表-批量删除")
    @RequiresPermissions("wmhb:wm_project:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> oldIdList = Arrays.asList(ids.split(","));
        List<String> newIdList = new ArrayList<>();
        List<String> filterIdList = new ArrayList<>();
        for (String id : oldIdList) {
            if (!wmProjectService.checkHasItem(id)) {
                newIdList.add(id);
            } else {
                filterIdList.add(id);
            }
        }

        String filterStr = String.join(",", filterIdList);
        if (!CollectionUtils.isEmpty(newIdList)) {
            this.wmProjectService.removeByIds(newIdList);
            if (CollectionUtils.isEmpty(filterIdList)) {
                return Result.OK("批量删除成功！");
            } else {
                String newStr = String.join(",", newIdList);
                return Result.OK("ID为" + newStr + "批量删除成功，ID为" + filterStr + "的删除失败，原因：项目下有合同！");
            }
        } else {
            return Result.error("批量删除失败，原因：项目下有合同！");
        }
    }

    /**
     * 通过id查询
     *
     * @param currentProjectId
     * @return
     */
    //@AutoLog(value = "项目表-通过id查询")
    @Operation(summary = "项目表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmProject> queryById(@RequestParam(name = "currentProjectId", required = true) String currentProjectId) {
        WmProject wmProject = wmProjectService.getById(currentProjectId);
        if (wmProject == null) {
            return Result.error("未找到对应数据");
        }

        return Result.OK(wmProject);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wmProject
     */
    @RequiresPermissions("wmhb:wm_project:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmProject wmProject) {
        return super.exportXls(request, wmProject, WmProject.class, "项目表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("wmhb:wm_project:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WmProject.class);
    }

    /**
     * 确认
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目表-确认")
    @Operation(summary = "项目表-确认")
    @RequiresPermissions("wmhb:wm_project:confirm")
    @Transactional
    @RequestMapping(value = "/confirm", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> doConfirm(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            WmProject wmProject = wmProjectService.getById(id);
            if (!wmProject.getStatus().equals(UserConstant.PROJECT_STATUS_PREPARE)) {
                {
                    throw new RuntimeException("只有草稿状态能确认");
                }
            }

            //wmProject.setProgress("10");
            wmProject.setStatus(UserConstant.PROJECT_STATUS_CONFIRMED); //更新项目的状态
            wmProjectService.updateById(wmProject);
        }
        return Result.OK("操作成功");
    }

    /**
     * 完成
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目表-完成")
    @Operation(summary = "项目表-完成")
    @RequiresPermissions("wmhb:wm_project:finish")
    @Transactional
    @RequestMapping(value = "/finish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> doFinish(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            WmProject wmProject = wmProjectService.getById(id);
            if (!wmProject.getStatus().equals(UserConstant.PROJECT_STATUS_CONFIRMED)) {
                {
                    throw new RuntimeException("只有确认状态能确认");
                }
            }

            wmProject.setProgress("100");
            wmProject.setStatus(UserConstant.PROJECT_STATUS_FINISHED); //更新项目的状态
            wmProjectService.updateById(wmProject);
        }
        return Result.OK("操作成功");
    }
}
